<template>
  <div class="functionType">
    <div class="titleTop first">
      <h3>{{$t('position_management.edit_position')}}</h3>
      <!-- <a-button v-if="twoArrCludes(['SITE_MANAGER'])" @click="addPosition">新增职位</a-button> -->
    </div>
    <div class="content">
      <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" class="formStyle">
        <a-row :gutter="10">
          <a-col :span="18">
            <iframe :src="iframeSrc" ref="iframeResume" frameborder="0" scrolling="auto" align="center" style="width:100%;min-height:500px"></iframe>
          </a-col>
          <a-col :span="6">
            <div class="positionSetting">
              <a-card :title="$t('navigation.post_release')" :bordered="false" style="width: 100%" class="lineP">
                <p class="publishInfo" v-if="positionData.user && positionData.user.name">{{ positionData.user.name }} {{$t('position_management.creat_position')}}</p>
                <p class="publishInfo">{{$t('position_management.date_published')}}：{{ positionData.datePublished | dateYYMMDD }}</p>
                <p class="publishInfo">{{$t('position_management.end_date')}}：{{ positionData.endDate | dateYYMMDD }}</p>
                <p class="publishInfo">{{$t('common.status')}}：<span v-if="whetherShown" class="statusBtn" :style="`background: ${positionData.drop ? 'red' : positionData.auditStatus === 'WAITAUDIT' ? '#0084cf' : positionData.auditStatus === 'FAILAUDIT' ? '#7d7b7b' : positionData.status === 'PUBLISHING' ? '#0084cf' : (positionData.status === 'PAUSE' || positionData.status === 'REVOKED') ? 'red' : '#0084cf'}`" v-html="$t(transition(positionData))"></span></p>
                <p class="publishInfo">{{$t('position_management.apply_count')}}：<a style="text-decoration: underline;" @click="clickApplyCount">{{ positionData.applyCount }}</a></p>
                <template class="ant-card-actions" slot="actions">
                  <span v-if="twoArrCludes(['NORMAL', 'COMPANY_MANAGER']) && positionOperationType !== 'add'">
                    <a-popconfirm
                      :title="`${$t('position_management.confirm_delete_postion')}?`"
                      @confirm="deleteAcct"
                      :okText="$t('common.confirm')"
                      :cancelText="$t('common.cancel')"
                    >
                      <a href="javascript:;" class="red">{{$t('common.delete')}}</a>
                    </a-popconfirm>
                  </span>
                  <span v-for="item in filterBtn(operateBtn)" :key="item.id" class="info_text" @click="changeStatus(item.id)" style="height:25px;" :loading="publishLoading">
                    {{ $t(item.name) }}
                  </span>
                  <span class="info_text" @click="publishFn" style="height:25px;" :loading="publishLoading">
                    {{ positionOperationType === 'add' || positionData.status !== 'PUBLISHING' ? $t('common.publish') : $t('common.save') }}
                  </span>
                </template>
              </a-card>
              <a-card :title="$t('position_management.position_nav')" class="navBar">
                <a-pagination simple :current="current" :pageSize="1" :total="max" @change="pageChange"/>
              </a-card>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <checked-reason :showReason="showReason" @confirm="faildConfirm"/>
  </div>
</template>

<script>
import dateFilter from '@/util/date'
import { positionPositionDetail, modifyStatus, auditPosition } from '@/api/position'
import { twoArrCludes, filterBtn } from '@/util/roles'
import CheckedReason from '@/components/position/CheckedReason'
let timer = null
const operateBtnAll = [{
  name: 'position_management.publish',
  id: 'PUBLISHING'
}, {
  name: 'position_management.revoked',
  // roles: ['NORMAL', 'COMPANY_MANAGER'],
  id: 'REVOKED'
}]
export default {
  name: 'functionType',
  components: { CheckedReason },
  data () {
    return {
      showReason: false,
      operateBtnAll,
      operateBtn: [],
      spinning: false,
      positionId: '',
      recruitmentTypeId: '',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      positionData: {},
      max: 0,
      current: 1,
      listId: [],
      iframeSrc: '',
      publishLoading: false,
      positionOperationType: 'edit'
    }
  },
  watch: {
    $route: {
      handler (val, oldVal) {
        if (val.query.pid !== oldVal.query.pid) {
          if (this.$route.query.pid) {
            this.positionId = this.$route.query.pid
          }
          if (this.$route.query.recruitmentTypeId) {
            this.recruitmentTypeId = this.$route.query.recruitmentTypeId
          }
          this.fetchPositionById()
        }
      },
      deep: true
    }
  },
  computed: {
    whetherShown () {
      return this.positionData.drop || this.positionData.auditStatus === 'WAITAUDIT' || this.positionData.auditStatus === 'FAILAUDIT' || this.positionData.status === 'PUBLISHING' || this.positionData.status === 'PAUSE' || this.positionData.status === 'REVOKED'
    }
  },
  filters: {
    ...dateFilter
  },
  created () {
    if (this.$route.query.pid) {
      this.positionId = this.$route.query.pid
    }
    if (this.$route.query.recruitmentTypeId) {
      this.recruitmentTypeId = this.$route.query.recruitmentTypeId
    }
    if (this.$route.query.type === 'addPosition') {
      this.positionOperationType = 'add'
      this.iframeSrc = `#/iframeEditPosition/addPosition`
    }
    if (this.positionId) {
      this.initDta()
    }
  },
  mounted () {
    window.addEventListener('message', (val) => {
      this.publishLoading = false
      if (val.data === 'warning') {
        this.debounce('warning', 500)
      } else if (val.data === 'success') {
        // VBUS.$emit('deleteSuccess', true)
        // this.debounce('success', 500)
        this.$router.push('/myPosition')
      } else if (val.data === 'failed') {
        this.debounce('failed', 500)
      }
    })
    this.$nextTick(() => {
      this.$refs.iframeResume.onload = () => {
        setTimeout(this.setIframeHeight, 2000)
      }
    })
  },
  methods: {
    filterBtn,
    twoArrCludes,
    transition (val) {
      if (val.status === 'PUBLISHING') {
        return 'position_management.topublishing'
      } else {
        return 'position_management.revokeding'
      }
    },
    faildConfirm ({ flag, reasonContent }) {
      if (flag) {
        this.sendAuditPosition('FAILAUDIT', reasonContent)
      } else {
        this.showReason = false
      }
    },
    changeStatus (status) {
      if (status === 'PUBLISHING1') { // PUBLISHING1为点击审核状态 PUBLISHING为点击发布状态
        status = status === 'PUBLISHING1' ? 'PUBLISHING' : status
        this.sendAuditPosition(status)
      } else if (status === 'FAILAUDIT') {
        this.showReason = true
      } else {
        this.sendModifyStatus(status)
      }
    },
    async sendModifyStatus (status) {
      let params = {
        status,
        positionList: [{ enterpriseId: this.positionData.enterpriseId, positionId: this.positionData.id }]
      }
      let res = await modifyStatus(params)
      if (res.code === 200) {
        if (res.tips) {
          this.$message.success(res.tips)
        } else {
          this.$message.success(res.message)
        }
        this.fetchPositionById()
      } else {
        this.$message.error(res.message)
      }
    },
    async sendAuditPosition (status, auditFailReason) {
      let params = {
        auditFailReason,
        status,
        positionList: [{ enterpriseId: this.positionData.enterpriseId, positionId: this.positionData.id }]
      }
      let res = await auditPosition(params)
      if (res.code === 200) {
        this.showReason = false
        this.$message.success(res.message)
        this.fetchPositionById()
      } else {
        this.$message.error(res.message)
      }
    },
    fetchPositionById () {
      positionPositionDetail({
        positionId: this.positionId
      }).then(res => {
        if (res.code === 200) {
          this.positionData = res.data
          this.operateBtn = this.operateBtnAll.filter(item => {
            if (item.id === 'PUBLISHING') { // 发布
              return this.positionData.status !== 'PUBLISHING'
            } else if (item.id === 'REVOKED') { // 下线
              return this.positionData.status === 'PUBLISHING'
            } else {
              return true
            }
          })
          console.log(this.positionData)
          this.$nextTick(function () {
            this.form.setFieldsValue(this.positionData)
          })
          this.iframeSrc = `#/iframeEditPosition/${this.positionId}/${this.recruitmentTypeId}`
        }
      }).catch(e => {
        this.spinning = false
      })
    },
    initDta () {
      if (!this.$route.query.pid) {
        return
      }
      let positionList = JSON.parse(sessionStorage.getItem('positionList'))
      this.listId = positionList ? positionList.list : []
      this.max = this.listId.length
      this.listId.forEach((ele, index) => {
        if (ele.id === this.$route.query.pid) {
          this.current = (index * 1) + 1
        }
      })
      this.fetchPositionById()
    },
    setIframeHeight () {
      let iframe = this.$refs.iframeResume
      if (iframe) {
        var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow
        if (iframeWin.document.body && iframeWin.document.querySelector('.iframeEditPositionBox')) {
          iframe.height = iframeWin.document.querySelector('.iframeEditPositionBox').offsetHeight || iframeWin.document.querySelector('.iframeEditPositionBox').offsetHeight
        }
      }
    },
    clickApplyCount () {
      this.$router.push(`/resume/candidateApplication?positionId=${this.positionId}`)
    },
    pageChange (current, pageSize) { // listId
      this.current = current
      this.$router.push({ query: { pid: this.listId[current - 1].id, recruitmentTypeId: this.listId[current - 1].recruitmentTypeId } })
    },
    publishFn () { // 发布
      this.publishLoading = true
      let mapFrame = this.$refs['iframeResume']
      let iframeWin = mapFrame.contentWindow
      iframeWin.postMessage('clickPublish', '*')
    },
    async deleteAcct () {
      let params = {
        status: 'DROP',
        positionList: [{ enterpriseId: this.positionData.enterpriseId, positionId: this.positionData.id }]
      }
      let res = await modifyStatus(params)
      if (res.code === 200) {
        this.$router.push('/position/positionManagement')
        VBUS.$emit('deleteSuccess', true)
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    },
    debounce (text, time) {
      if (timer) clearTimeout(timer)
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, time)
      if (callNow) {
        if (text === 'success') {
          this.$message.success(`${this.$t('common.success')}！`)
        } else if (text === 'warning') {
          this.$message.warning(`${this.$t('common.confirm_require')}！`)
        } else if (text === 'failed') {
          this.$message.warning(`${this.$t('message.failed')}！`)
        }
      }
    },
    addPosition () {
      this.$router.push(`/position/positionEditing?type=addPosition`)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.functionType
  .lineP
    p
      line-height 28px
  .titleTop
    background #fff
    display flex
    align-items center
    justify-content flex-start
    padding  0 24px 12px
    h3
      margin-right 24px
      font-size 18px
      font-weight bold
    button
      margin-left 12px
  .content
    padding 12px 24px
    display flex
    justify-content space-between
    iframe
      flex 1
  :global(.CandidateTable)
    margin-top 12px
  .formStyle
    width 100%
  .formStyle .positionInfo :global(.ant-card-body)
    padding 0px
  .navBar
    margin-top 10px
    :global(.ant-card-body)
      text-align center
  .red
    color errorColor
  .under
    cursor pointer
    text-decoration underline
  .statusBtn
    display inline-block
    border-radius: 15px;
    padding: 2px 8px;
    height: 24px;
    color #fff
    text-align center
    line-height 20px
</style>
